package com.wingscode.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wingscode.common.utils.R;
import com.wingscode.modules.app.annotation.Login;
import com.wingscode.modules.app.form.UserInfoForm;
import com.wingscode.modules.common.entity.*;
import com.wingscode.modules.common.service.*;
import com.wingscode.modules.sys.entity.AgentApplyEntity;
import com.wingscode.modules.sys.entity.RegionEntity;
import com.wingscode.modules.sys.service.AgentApplyService;

import com.wingscode.modules.sys.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 我的、报价设置
 *
 * @author yan
 */
@RestController
@RequestMapping("/app/4")
@Api("我的、报价设置")
public class AppController4 {
    @Autowired
    private UserService userService;
    @Autowired
    private AgentApplyService agentApplyService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private UserSettingService userSettingService;
    @Autowired
    private RegionService regionService;

    @PostMapping("updateUserInfo")
    @ApiOperation("更新用户信息")
    public R updateUser(@RequestBody UserEntity entity) {
        if (entity.getId() == null)
            return R.error("id为空");

        UserEntity user = userService.getById(entity.getId());
        if (user != null) {
            user.setUsername(entity.getUsername());
            user.setAvatar(entity.getAvatar());

            userService.updateById(user);
        }

        // 获得企业认证状态
        if (user.getAgentId() != null) {
            AgentEntity agentEntity = agentService.getById(user.getAgentId());
            if (agentEntity != null) {
                user.setAgentState(agentEntity.getState());
                user.setAgentName(agentEntity.getCompany());
                user.setLevel(agentEntity.getLevel());
            }
        }
        UserInfoForm userInfoForm = new UserInfoForm().getUserInfo(user);

        return R.ok(200, userInfoForm);
    }

    @GetMapping("/apply")
    @ApiOperation("渠道用户申请")
    public R apply(@RequestParam Integer agentId) {
        if (agentId == null)
            return R.error("agentId为空");

        // 检查当前用户是否已申请渠道用户
        List<AgentApplyEntity> applyList = agentApplyService.list(
                new QueryWrapper<AgentApplyEntity>()
                        .eq("agent_id", agentId)
                        .eq("state", 0)
        );
        if (applyList != null && applyList.size() > 0)
            return R.error("您已经申请，待实地考察后您即可成为渠道用户");

        AgentApplyEntity entity = new AgentApplyEntity();
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setAgentId(agentId);
        entity.setState(0);

        agentApplyService.save(entity);

        return R.ok();
    }

    @PostMapping("saveSendType")
    @ApiOperation("保存报价类型设置")
    public R saveSendType(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId"))
            return R.error("userId为空");
        if (!params.containsKey("agentId"))
            return R.error("agentId为空");
        if (!params.containsKey("sendType"))
            return R.error("sendType为空");

        Integer userId = null, agentId = null;
        String sendType = "";

        userId = Integer.parseInt(params.get("userId").toString());
        agentId = Integer.parseInt(params.get("agentId").toString());
        sendType = (String) params.get("sendType");

        UserSettingEntity entity = new UserSettingEntity();

        // 检查是否存在报价类型数据
        List<UserSettingEntity> list = userSettingService.list(
                new QueryWrapper<UserSettingEntity>()
                        .eq("user_id", userId)
                        .eq("agent_id", agentId)
        );

        if (list != null && list.size() > 0) {
            entity = list.get(0);

            entity.setSendType(sendType);

            userSettingService.updateById(entity);
        } else {
            entity.setUserId(userId);
            entity.setAgentId(agentId);
            entity.setSendType(sendType);

            userSettingService.save(entity);
        }

        return R.ok();
    }

    @GetMapping("getSendType")
    @ApiOperation("获得报价类型设置")
    public R getSendType(@RequestParam Integer userId) {
        if (userId == null)
            return R.error("userId为空");

        List<UserSettingEntity> list = userSettingService.list(
                new QueryWrapper<UserSettingEntity>()
                        .eq("user_id", userId)
        );

        if (list != null && list.size() > 0)
            return R.ok(200, list.get(0));

        return R.ok();
    }

    @GetMapping("getCityList")
    @ApiOperation("获得城市列表")
    public R getCityList() {
        List<RegionEntity> list = regionService.list(
                new QueryWrapper<RegionEntity>()
                        .eq("pid", 0)
                        .orderByAsc("sort")
        );
        if (list != null && list.size() > 0) {
            for (RegionEntity entity : list) {
                List<RegionEntity> childList = regionService.list(
                        new QueryWrapper<RegionEntity>()
                                .eq("pid", entity.getId())
                                .orderByAsc("sort")
                );

                entity.setChildList(childList);
            }
        }

        return R.ok(200, list);
    }

    @GetMapping("getChooseCityList")
    @ApiOperation("获得已选城市")
    public R getChooseCityList(@RequestParam Integer userId) {
        if (userId == null)
            return R.error("userId为空");

        List<RegionEntity> list = regionService.getChooseCityList(userId);

        return R.ok(200, list);
    }

    @PostMapping("saveRegion")
    @ApiOperation("保存区域设置")
    public R saveRegion(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId"))
            return R.error("userId为空");
        if (!params.containsKey("agentId"))
            return R.error("agentId为空");
        if (!params.containsKey("areaId"))
            return R.error("areaId为空");

        Integer userId = null, agentId = null;
        String areaId = "";

        userId = Integer.parseInt(params.get("userId").toString());
        agentId = Integer.parseInt(params.get("agentId").toString());
        areaId = (String) params.get("areaId");

        UserSettingEntity entity = new UserSettingEntity();

        // 检查是否存在地区设置数据
        List<UserSettingEntity> list = userSettingService.list(
                new QueryWrapper<UserSettingEntity>()
                        .eq("user_id", userId)
                        .eq("agent_id", agentId)
        );

        if (list != null && list.size() > 0) {
            entity = list.get(0);

            if (entity.getAreaId() == null || entity.getAreaId().isEmpty() || entity.getAreaId().length() == 0)
                entity.setAreaId(areaId);
            else
                entity.setAreaId(entity.getAreaId() + "," + areaId);

            userSettingService.updateById(entity);
        } else {
            entity.setUserId(userId);
            entity.setAgentId(agentId);
            entity.setSendType(areaId);

            userSettingService.save(entity);
        }

        return R.ok();
    }

    @PostMapping("deleteRegion")
    @ApiOperation("删除区域设置")
    public R deleteRegion(@RequestBody Map<String, Object> params) {
        String areaStr = "";
        if (!params.containsKey("userId"))
            return R.error("userId为空");
        if (!params.containsKey("agentId"))
            return R.error("agentId为空");
        if (!params.containsKey("areaId"))
            return R.error("areaId为空");

        Integer userId = null, agentId = null, areaId = null;

        userId = Integer.parseInt(params.get("userId").toString());
        agentId = Integer.parseInt( params.get("agentId").toString());
        areaId = Integer.parseInt(params.get("areaId").toString());

        // 检查是否存在地区设置数据
        List<UserSettingEntity> list = userSettingService.list(
                new QueryWrapper<UserSettingEntity>()
                        .eq("user_id", userId)
                        .eq("agent_id", agentId)
        );

        if (list != null && list.size() > 0) {
            UserSettingEntity entity = list.get(0);
            String[] array = entity.getAreaId().split(",");

            if (array != null && array.length > 0) {
                for (String arr : array) {
                    if (!arr.equals(areaId.toString()))
                        areaStr += arr + ",";
                }

                if (areaStr.length() > 0)
                    entity.setAreaId(areaStr.substring(0, areaStr.length() - 1));
            }

            userSettingService.updateById(entity);
        }

        return R.ok();
    }

}
